package com.emm.yixun.mobile.ui.analysis;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.MainProjectAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetDealHouseTypeList;
import com.emm.yixun.mobile.model.GetProjectList;
import com.emm.yixun.mobile.model.GetProjectList.ProjectList;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.PercentFormatter;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 成交房产类型分析
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午4:12:35
 */
public class HousingTypeAnalySisActivity extends SwipeBackActivity implements OnChartValueSelectedListener {

	private static final String TAG = "HousingTypeAnalySisActivity";

	/** 标题 */
	TextView title_main;

	TextView null_date3;

	/** Back按钮 */
	ImageView back_btn;

	LinearLayout open_layout_analysis;

	TextView name_time_analysis;

	/** 扇形图 */
	private PieChart mChart;

	/** 数据列表 */
	private ArrayList<String> list = new ArrayList<String>();
	private ArrayList<String> list3 = new ArrayList<String>();

	/** 数据列表每项所对应的百分比 */
	private ArrayList<Float> list2 = new ArrayList<Float>();

	/** 侧滑关闭框架 */
	private SwipeBackLayout mSwipeBackLayout;
	
	@Override
	protected void onResume() {
		BaseActivity.activity = this; // TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.housing_type_activity);
		
		SetSwipeBackLayout(mSwipeBackLayout);
		
		BaseActivity.activity = this;

		SetColor();
		initView();

		SetRelativiLayoutPadding(R.id.main_head_top_rela);
		
		initBtn();

		getDealHouseTypeList("1");
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午3:33:22
	 */
	private void initView() {
		title_main = (TextView) findViewById(R.id.title_main);
		title_main.setText("成交房产类型分析");
		back_btn = (ImageView) findViewById(R.id.back_btn);
		open_layout_analysis = (LinearLayout) findViewById(R.id.open_layout_analysis);
		name_time_analysis = (TextView) findViewById(R.id.name_time_analysis);
		null_date3 = (TextView) findViewById(R.id.null_date3);
		mChart = (PieChart) findViewById(R.id.chart1);
		mChart.setNoDataText(" ");

	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化监听事件
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午3:33:29
	 */
	private void initBtn() {
		back_btn.setVisibility(View.VISIBLE);
		back_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		open_layout_analysis.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SetsortPopu();
			}
		});
	}

	private void MarkChart() {
		list.clear();
		list2.clear();
		for (int i = 0; i < 4; i++) {
			list.add("第" + i + "个");
			list2.add(Float.valueOf((i + 1) * 3 / 2));
		}
		SetSettingChart(0);
		animate();
	}

	View viewproject;
	PopupWindow popuproject;
	/** 时间 */
	private int SelectPostion = 0;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 条件筛选弹出框
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午3:33:42
	 */
	public void SetsortPopu() {
		viewproject = LayoutInflater.from(HousingTypeAnalySisActivity.this).inflate(R.layout.mainproject_popu, null);
		popuproject = new PopupWindow(viewproject, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
				android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
		popuproject.setFocusable(true);
		popuproject.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
		popuproject.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		popuproject.showAtLocation(open_layout_analysis, Gravity.TOP, 0, 0);
		popuproject.setFocusable(true);
		popuproject.setOutsideTouchable(true);
		viewproject.setFocusable(true);
		viewproject.setFocusableInTouchMode(true);
		viewproject.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					popuproject.dismiss();
					EmmApplication.setLog(HousingTypeAnalySisActivity.this);
				}
				return false;
			}
		});

		viewproject.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popuproject.dismiss();
				EmmApplication.setLog(HousingTypeAnalySisActivity.this);
			}
		});

		ListView popu_list = (ListView) viewproject.findViewById(R.id.popu_list);
		RelativeLayout top_relativelayout = (RelativeLayout) viewproject.findViewById(R.id.top_relativelayout);
		SetViewPaddingHeight(top_relativelayout, 100);
		ArrayList<ProjectList> ll = new ArrayList<ProjectList>();

		ProjectList m = new ProjectList();
		m.setProjectCode("1");
		m.setProjectName("今天");
		ll.add(m);

		ProjectList m2 = new ProjectList();
		m2.setProjectCode("2");
		m2.setProjectName("昨天");
		ll.add(m2);

		ProjectList m3 = new ProjectList();
		m3.setProjectCode("3");
		m3.setProjectName("本周");
		ll.add(m3);

		ProjectList m4 = new ProjectList();
		m4.setProjectCode("4");
		m4.setProjectName("上周");
		ll.add(m4);

		ProjectList m5 = new ProjectList();
		m5.setProjectCode("5");
		m5.setProjectName("本月");
		ll.add(m5);

		ProjectList m6 = new ProjectList();
		m6.setProjectCode("6");
		m6.setProjectName("上月");
		ll.add(m6);

		ProjectList m7 = new ProjectList();
		m7.setProjectCode("7");
		m7.setProjectName("近三月");
		ll.add(m7);

		ProjectList m8 = new ProjectList();
		m8.setProjectCode("8");
		m8.setProjectName("今年");
		ll.add(m8);

		final GetProjectList list = new GetProjectList();
		list.setProjectList(ll);

		MainProjectAdapter adapter = new MainProjectAdapter(HousingTypeAnalySisActivity.this, list);
		popu_list.setAdapter(adapter);
		adapter.SetType(1);
		if (list.getProjectList().size() >= (SelectPostion + 1)) {
			adapter.SeleCt(SelectPostion);
			name_time_analysis.setText(list.getProjectList().get(SelectPostion).getProjectName());
		} else {
			adapter.SeleCt(0);
			name_time_analysis.setText(list.getProjectList().get(0).getProjectName());
		}
		popu_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				popuproject.dismiss();
				SelectPostion = position;
				EmmApplication.setLog(HousingTypeAnalySisActivity.this);
				name_time_analysis.setText(list.getProjectList().get(position).getProjectName());
				int numbertype = SelectPostion + 1;
				Log.v(TAG, "numbertype:==>" + numbertype);
				// 调用接口
				getDealHouseTypeList("" + numbertype);
			}
		});
	}

	/**
	 * 成交房源数据
	 */
	GetDealHouseTypeList getdealhouse;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 成交房源数据
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param workloadTimeType
	 * @author tangxin
	 * @date 2016年12月7日 下午3:34:17
	 */
	private void getDealHouseTypeList(String workloadTimeType) {
		EmmApplication.updateUrl("getDealHouseTypeList");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("workloadTimeType", workloadTimeType);
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("getDealHouseTypeList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.hideDialogForLoading();
				Loading.showDialogForLoading(HousingTypeAnalySisActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v(TAG, "content===>" + content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getdealhouse = JSONObject.parseObject(resData.toString(), GetDealHouseTypeList.class);

				if ("1".equals(getdealhouse.getResult())) {
					Log.v("获取成功", "");
					if (null != getdealhouse.getDealHouseTypeList()) {
						list.clear();
						list2.clear();
						list3.clear();
						double countall = 0;
						for (int i = 0; i < getdealhouse.getDealHouseTypeList().size(); i++) {
							countall += Double.valueOf(getdealhouse.getDealHouseTypeList().get(i).getDealHouseTypeNum()).doubleValue();
						}
						for (int i = 0; i < getdealhouse.getDealHouseTypeList().size(); i++) {
							list.add(getdealhouse.getDealHouseTypeList().get(i).getDealHouseTypeName());
							list2.add((float) (Double.valueOf(getdealhouse.getDealHouseTypeList().get(i).getDealHouseTypeNum())
									.doubleValue() / countall) * 100);
							list3.add(getdealhouse.getDealHouseTypeList().get(i).getDealHouseTypeNum());
							// 需要计算百分比
						}
						if (list.size() <= 0) {
							null_date3.setVisibility(View.VISIBLE);
						} else {
							null_date3.setVisibility(View.GONE);
							SetSettingChart(0);
							animate();
						}
					} else {
						null_date3.setVisibility(View.VISIBLE);
						EmmApplication.T("获取数据为空");
						list.clear();
						list3.clear();
						list2.clear();
						SetSettingChart(1);
						animate();
					}
				} else {
					EmmApplication.T(getdealhouse.getErrorMsg().toString());
					Log.v("获取失败", "errorCode:" + getdealhouse.getErrorCode().toString() + "errorMsg:"
							+ getdealhouse.getErrorMsg().toString());
				}
			}
		});
	}

	/**
	 * 
	 * <p><b>Title：</b> 配置扇形图属性,第一次在加载数据完成之后触发</p>
	 * <p><b>Description：</b> </p>
	 * @param type
	 * @author tangxin
	 * @date 2016年12月7日 下午3:34:31
	 */
	private void SetSettingChart(int type) {
		mChart.setUsePercentValues(true);
		mChart.setHoleColorTransparent(true);
		mChart.setHoleRadius(55);
		if (type == 0) {
			mChart.setHoleColor(Color.parseColor("#ffffff"));
			mChart.setCenterText("100%");
		} else {
			mChart.setHoleColor(Color.parseColor("#00ffffff"));
			mChart.setCenterText(" ");
		}
		mChart.setDescription("");
		mChart.setDrawCenterText(true);
		mChart.setDrawHoleEnabled(true);
		mChart.setRotationAngle(0);
		mChart.setRotationEnabled(true);
		mChart.setOnChartValueSelectedListener(this);
		mChart.setX(EmmApplication.dip2px(-50));
		setData();
		mChart.animateXY(1000, 1000);
		Legend l = mChart.getLegend();
		l.setPosition(LegendPosition.RIGHT_OF_CHART);
		l.setXEntrySpace(20f);
		l.setYEntrySpace(4f);
	}

	/**
	 * 
	 * <p><b>Title：</b> 调用动画效果</p>
	 * <p><b>Description：</b> </p>
	 * @author tangxin
	 * @date 2016年12月7日 下午3:34:39
	 */
	private void animate() {
		mChart.invalidate();
	}

	public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
		if (e == null)
			return;
		Log.i("VAL SELECTED", "Value: " + e.getVal() + ", xIndex: " + e.getXIndex() + ", DataSet index: " + dataSetIndex);
	}

	public void onNothingSelected() {
		Log.i("PieChart", "nothing selected");
	}

	/**
	 * 
	 * <p><b>Title：</b> 给统计图配置数据</p>
	 * <p><b>Description：</b> </p>
	 * @author tangxin
	 * @date 2016年12月7日 下午3:34:48
	 */
	private void setData() {
		ArrayList<Entry> yVals1 = new ArrayList<Entry>();
		for (int i = 0; i < list2.size(); i++) {
			yVals1.add(new Entry(list2.get(i), i));
		}
		ArrayList<String> xVals = new ArrayList<String>();

		PieDataSet dataSet = new PieDataSet(yVals1, "");
		dataSet.setSliceSpace(3f);
		for (int i = 0; i < list.size(); i++)
			xVals.add(list.get(i) + "\t\t" + list3.get(i) + "\t\t" + ("(" + EmmApplication.drop2("" + list2.get(i)) + "%" + ")"));
		dataSet.setDrawValues(false);
		mChart.setDrawSliceText(false);
		ArrayList<Integer> colors = new ArrayList<Integer>();

		for (int i = 0; i < list.size(); i++) {
			colors.add(bgcolor.get(i));
		}

		dataSet.setColors(colors);
		PieData data = new PieData(xVals, dataSet);
		data.setValueFormatter(new PercentFormatter());
		data.setValueTextSize(11f);
		data.setValueTextColor(Color.BLACK);
		mChart.setData(data);
		mChart.highlightValues(null);
		mChart.setNoDataTextDescription(" ");
		mChart.invalidate();
	}

	ArrayList<Integer> bgcolor = new ArrayList<Integer>();

	/**
	 * 
	 * <p><b>Title：</b> 初始化展示色值</p>
	 * <p><b>Description：</b> </p>
	 * @author tangxin
	 * @date 2016年12月7日 下午3:35:12
	 */
	private void SetColor() {
		bgcolor.add(Color.parseColor("#FFE76E"));
		bgcolor.add(Color.parseColor("#FFC499"));
		bgcolor.add(Color.parseColor("#FFB468"));
		bgcolor.add(Color.parseColor("#FF9048"));
		bgcolor.add(Color.parseColor("#F64A2A"));
		bgcolor.add(Color.parseColor("#FA7388"));
		bgcolor.add(Color.parseColor("#F63C7F"));
		bgcolor.add(Color.parseColor("#F43560"));
		bgcolor.add(Color.parseColor("#CC1F1A"));
		bgcolor.add(Color.parseColor("#740D0C"));
		bgcolor.add(Color.parseColor("#C6F4FF"));
		bgcolor.add(Color.parseColor("#67C3D5"));
		bgcolor.add(Color.parseColor("#5199AA"));
		bgcolor.add(Color.parseColor("#009796"));
		bgcolor.add(Color.parseColor("#009868"));
		bgcolor.add(Color.parseColor("#8CD3E7"));
		bgcolor.add(Color.parseColor("#1FBBD3"));
		bgcolor.add(Color.parseColor("#006EA8"));
		bgcolor.add(Color.parseColor("#005AA6"));
		bgcolor.add(Color.parseColor("#5B5377"));
	}

}
